#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
商业洞察生成器

根据优化方案实现的商业洞察深度分析：
1. 决策影响分析器 - 分析决策对业务的影响
2. 风险评估器 - 识别和评估业务风险
3. 机会识别器 - 发现业务机会
4. 建议生成器 - 生成可执行的商业建议
"""

import logging
import numpy as np
import pandas as pd
from typing import Dict, List, Any, Optional, Tuple, Union
from dataclasses import dataclass, field
from enum import Enum
import json
from datetime import datetime, timedelta
from collections import defaultdict
import statistics


class RiskLevel(Enum):
    """风险等级"""
    LOW = "低风险"
    MEDIUM = "中等风险"
    HIGH = "高风险"
    CRITICAL = "严重风险"


class OpportunityType(Enum):
    """机会类型"""
    COST_REDUCTION = "成本降低"
    REVENUE_INCREASE = "收入增长"
    EFFICIENCY_IMPROVEMENT = "效率提升"
    QUALITY_ENHANCEMENT = "质量改善"
    RISK_MITIGATION = "风险缓解"
    MARKET_EXPANSION = "市场扩张"


class ImpactCategory(Enum):
    """影响类别"""
    FINANCIAL = "财务影响"
    OPERATIONAL = "运营影响"
    STRATEGIC = "战略影响"
    CUSTOMER = "客户影响"
    COMPLIANCE = "合规影响"
    REPUTATION = "声誉影响"


@dataclass
class BusinessMetrics:
    """业务指标"""
    revenue: float = 0.0
    cost: float = 0.0
    profit: float = 0.0
    profit_margin: float = 0.0
    roi: float = 0.0
    efficiency_score: float = 0.0
    quality_score: float = 0.0
    customer_satisfaction: float = 0.0
    market_share: float = 0.0
    risk_score: float = 0.0
    
    def __post_init__(self):
        if self.profit == 0.0 and self.revenue > 0 and self.cost > 0:
            self.profit = self.revenue - self.cost
        if self.profit_margin == 0.0 and self.revenue > 0:
            self.profit_margin = self.profit / self.revenue * 100


@dataclass
class RiskAssessment:
    """风险评估"""
    risk_id: str
    description: str
    category: str
    probability: float  # 0-1
    impact: float  # 0-1
    risk_level: RiskLevel
    mitigation_strategies: List[str] = field(default_factory=list)
    estimated_cost: float = 0.0
    timeline: str = ""
    
    @property
    def risk_score(self) -> float:
        """风险评分"""
        return self.probability * self.impact


@dataclass
class BusinessOpportunity:
    """商业机会"""
    opportunity_id: str
    description: str
    opportunity_type: OpportunityType
    potential_value: float
    implementation_cost: float
    timeline: str
    success_probability: float  # 0-1
    required_resources: List[str] = field(default_factory=list)
    dependencies: List[str] = field(default_factory=list)
    
    @property
    def net_value(self) -> float:
        """净价值"""
        return self.potential_value - self.implementation_cost
    
    @property
    def expected_value(self) -> float:
        """期望价值"""
        return self.net_value * self.success_probability
    
    @property
    def roi_potential(self) -> float:
        """投资回报率潜力"""
        if self.implementation_cost > 0:
            return (self.potential_value / self.implementation_cost - 1) * 100
        return 0.0


@dataclass
class DecisionImpact:
    """决策影响"""
    decision_id: str
    description: str
    category: ImpactCategory
    short_term_impact: float  # 短期影响（1年内）
    medium_term_impact: float  # 中期影响（1-3年）
    long_term_impact: float  # 长期影响（3年以上）
    confidence_level: float  # 0-1
    affected_stakeholders: List[str] = field(default_factory=list)
    metrics_affected: List[str] = field(default_factory=list)
    
    @property
    def total_impact(self) -> float:
        """总影响（加权平均）"""
        return (self.short_term_impact * 0.5 + 
                self.medium_term_impact * 0.3 + 
                self.long_term_impact * 0.2)


@dataclass
class BusinessInsight:
    """商业洞察"""
    insight_id: str
    title: str
    description: str
    insight_type: str
    priority: str  # 高、中、低
    confidence: float  # 0-1
    supporting_data: Dict[str, Any] = field(default_factory=dict)
    recommendations: List[str] = field(default_factory=list)
    potential_impact: float = 0.0
    implementation_difficulty: str = "中等"
    timeline: str = ""


class DecisionImpactAnalyzer:
    """
    决策影响分析器
    """
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.impact_history = []
    
    def analyze_decision_impact(self, decision_data: Dict[str, Any], 
                              baseline_metrics: BusinessMetrics,
                              scenario_metrics: Dict[str, BusinessMetrics]) -> List[DecisionImpact]:
        """
        分析决策影响
        
        Args:
            decision_data: 决策数据
            baseline_metrics: 基准指标
            scenario_metrics: 各情景指标
            
        Returns:
            List[DecisionImpact]: 决策影响列表
        """
        impacts = []
        
        try:
            # 分析财务影响
            financial_impact = self._analyze_financial_impact(
                baseline_metrics, scenario_metrics
            )
            impacts.append(financial_impact)
            
            # 分析运营影响
            operational_impact = self._analyze_operational_impact(
                decision_data, baseline_metrics, scenario_metrics
            )
            impacts.append(operational_impact)
            
            # 分析战略影响
            strategic_impact = self._analyze_strategic_impact(
                decision_data, scenario_metrics
            )
            impacts.append(strategic_impact)
            
            # 分析客户影响
            customer_impact = self._analyze_customer_impact(
                baseline_metrics, scenario_metrics
            )
            impacts.append(customer_impact)
            
            self.impact_history.extend(impacts)
            
        except Exception as e:
            self.logger.error(f"决策影响分析失败: {e}")
        
        return impacts
    
    def _analyze_financial_impact(self, baseline: BusinessMetrics, 
                                scenarios: Dict[str, BusinessMetrics]) -> DecisionImpact:
        """
        分析财务影响
        """
        profit_changes = []
        roi_changes = []
        
        for scenario_name, metrics in scenarios.items():
            profit_change = ((metrics.profit - baseline.profit) / baseline.profit * 100 
                           if baseline.profit != 0 else 0)
            roi_change = metrics.roi - baseline.roi
            
            profit_changes.append(profit_change)
            roi_changes.append(roi_change)
        
        avg_profit_change = np.mean(profit_changes) if profit_changes else 0
        avg_roi_change = np.mean(roi_changes) if roi_changes else 0
        
        # 计算短期、中期、长期影响
        short_term = avg_profit_change * 0.8  # 短期影响较大
        medium_term = avg_profit_change * 1.0  # 中期影响稳定
        long_term = avg_profit_change * 1.2   # 长期影响可能放大
        
        return DecisionImpact(
            decision_id="financial_impact",
            description=f"决策对财务的影响：平均利润变化{avg_profit_change:.2f}%，ROI变化{avg_roi_change:.2f}%",
            category=ImpactCategory.FINANCIAL,
            short_term_impact=short_term,
            medium_term_impact=medium_term,
            long_term_impact=long_term,
            confidence_level=0.8,
            affected_stakeholders=["股东", "财务部门", "管理层"],
            metrics_affected=["利润", "ROI", "现金流"]
        )
    
    def _analyze_operational_impact(self, decision_data: Dict[str, Any],
                                  baseline: BusinessMetrics,
                                  scenarios: Dict[str, BusinessMetrics]) -> DecisionImpact:
        """
        分析运营影响
        """
        efficiency_changes = []
        quality_changes = []
        
        for scenario_name, metrics in scenarios.items():
            efficiency_change = metrics.efficiency_score - baseline.efficiency_score
            quality_change = metrics.quality_score - baseline.quality_score
            
            efficiency_changes.append(efficiency_change)
            quality_changes.append(quality_change)
        
        avg_efficiency_change = np.mean(efficiency_changes) if efficiency_changes else 0
        avg_quality_change = np.mean(quality_changes) if quality_changes else 0
        
        # 运营影响通常在中期最明显
        short_term = (avg_efficiency_change + avg_quality_change) * 0.6
        medium_term = (avg_efficiency_change + avg_quality_change) * 1.0
        long_term = (avg_efficiency_change + avg_quality_change) * 0.8
        
        return DecisionImpact(
            decision_id="operational_impact",
            description=f"决策对运营的影响：效率变化{avg_efficiency_change:.2f}，质量变化{avg_quality_change:.2f}",
            category=ImpactCategory.OPERATIONAL,
            short_term_impact=short_term,
            medium_term_impact=medium_term,
            long_term_impact=long_term,
            confidence_level=0.7,
            affected_stakeholders=["运营团队", "生产部门", "质量控制"],
            metrics_affected=["效率", "质量", "产能利用率"]
        )
    
    def _analyze_strategic_impact(self, decision_data: Dict[str, Any],
                                scenarios: Dict[str, BusinessMetrics]) -> DecisionImpact:
        """
        分析战略影响
        """
        # 基于决策复杂度和影响范围评估战略影响
        decision_complexity = len(decision_data.get('variables', []))
        scenario_variance = np.var([m.profit for m in scenarios.values()]) if scenarios else 0
        
        # 战略影响通常在长期更明显
        strategic_score = min(decision_complexity * 0.1 + scenario_variance * 0.001, 10)
        
        short_term = strategic_score * 0.3
        medium_term = strategic_score * 0.7
        long_term = strategic_score * 1.0
        
        return DecisionImpact(
            decision_id="strategic_impact",
            description=f"决策的战略影响：复杂度{decision_complexity}，方案差异性{scenario_variance:.2f}",
            category=ImpactCategory.STRATEGIC,
            short_term_impact=short_term,
            medium_term_impact=medium_term,
            long_term_impact=long_term,
            confidence_level=0.6,
            affected_stakeholders=["高级管理层", "战略规划部门", "董事会"],
            metrics_affected=["市场地位", "竞争优势", "长期增长"]
        )
    
    def _analyze_customer_impact(self, baseline: BusinessMetrics,
                               scenarios: Dict[str, BusinessMetrics]) -> DecisionImpact:
        """
        分析客户影响
        """
        satisfaction_changes = []
        
        for scenario_name, metrics in scenarios.items():
            satisfaction_change = metrics.customer_satisfaction - baseline.customer_satisfaction
            satisfaction_changes.append(satisfaction_change)
        
        avg_satisfaction_change = np.mean(satisfaction_changes) if satisfaction_changes else 0
        
        # 客户影响在中长期更明显
        short_term = avg_satisfaction_change * 0.5
        medium_term = avg_satisfaction_change * 1.0
        long_term = avg_satisfaction_change * 1.2
        
        return DecisionImpact(
            decision_id="customer_impact",
            description=f"决策对客户的影响：满意度变化{avg_satisfaction_change:.2f}",
            category=ImpactCategory.CUSTOMER,
            short_term_impact=short_term,
            medium_term_impact=medium_term,
            long_term_impact=long_term,
            confidence_level=0.7,
            affected_stakeholders=["客户", "销售团队", "客服部门"],
            metrics_affected=["客户满意度", "客户保留率", "品牌忠诚度"]
        )


class RiskAssessmentEngine:
    """
    风险评估引擎
    """
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.risk_database = self._initialize_risk_database()
    
    def _initialize_risk_database(self) -> Dict[str, Dict[str, Any]]:
        """
        初始化风险数据库
        """
        return {
            "financial_risk": {
                "indicators": ["profit_volatility", "cost_increase", "revenue_decline"],
                "thresholds": {"low": 0.1, "medium": 0.3, "high": 0.5},
                "mitigation": ["多元化投资", "成本控制", "收入来源分散"]
            },
            "operational_risk": {
                "indicators": ["efficiency_drop", "quality_issues", "capacity_constraints"],
                "thresholds": {"low": 0.05, "medium": 0.15, "high": 0.3},
                "mitigation": ["流程优化", "质量管理", "产能规划"]
            },
            "market_risk": {
                "indicators": ["market_share_loss", "competition_increase", "demand_volatility"],
                "thresholds": {"low": 0.05, "medium": 0.2, "high": 0.4},
                "mitigation": ["市场调研", "产品创新", "客户关系管理"]
            },
            "compliance_risk": {
                "indicators": ["regulation_changes", "audit_findings", "legal_issues"],
                "thresholds": {"low": 0.1, "medium": 0.3, "high": 0.6},
                "mitigation": ["合规培训", "内部审计", "法律咨询"]
            }
        }
    
    def assess_risks(self, decision_data: Dict[str, Any],
                    scenario_metrics: Dict[str, BusinessMetrics],
                    baseline_metrics: BusinessMetrics) -> List[RiskAssessment]:
        """
        评估风险
        
        Args:
            decision_data: 决策数据
            scenario_metrics: 情景指标
            baseline_metrics: 基准指标
            
        Returns:
            List[RiskAssessment]: 风险评估列表
        """
        risks = []
        
        try:
            # 评估财务风险
            financial_risks = self._assess_financial_risks(scenario_metrics, baseline_metrics)
            risks.extend(financial_risks)
            
            # 评估运营风险
            operational_risks = self._assess_operational_risks(scenario_metrics, baseline_metrics)
            risks.extend(operational_risks)
            
            # 评估市场风险
            market_risks = self._assess_market_risks(scenario_metrics, baseline_metrics)
            risks.extend(market_risks)
            
            # 评估合规风险
            compliance_risks = self._assess_compliance_risks(decision_data)
            risks.extend(compliance_risks)
            
        except Exception as e:
            self.logger.error(f"风险评估失败: {e}")
        
        return sorted(risks, key=lambda x: x.risk_score, reverse=True)
    
    def _assess_financial_risks(self, scenarios: Dict[str, BusinessMetrics],
                              baseline: BusinessMetrics) -> List[RiskAssessment]:
        """
        评估财务风险
        """
        risks = []
        
        # 计算利润波动性
        profits = [m.profit for m in scenarios.values()]
        if len(profits) > 1:
            profit_volatility = np.std(profits) / np.mean(profits) if np.mean(profits) != 0 else 0
            
            risk_level = self._determine_risk_level(profit_volatility, "financial_risk")
            
            risks.append(RiskAssessment(
                risk_id="profit_volatility",
                description=f"利润波动风险：标准差/均值 = {profit_volatility:.3f}",
                category="财务风险",
                probability=min(profit_volatility * 2, 1.0),
                impact=0.8,
                risk_level=risk_level,
                mitigation_strategies=self.risk_database["financial_risk"]["mitigation"],
                estimated_cost=baseline.profit * 0.1,
                timeline="短期-中期"
            ))
        
        # 评估成本上升风险
        cost_increases = []
        for scenario_name, metrics in scenarios.items():
            if baseline.cost > 0:
                cost_change = (metrics.cost - baseline.cost) / baseline.cost
                if cost_change > 0:
                    cost_increases.append(cost_change)
        
        if cost_increases:
            avg_cost_increase = np.mean(cost_increases)
            risk_level = self._determine_risk_level(avg_cost_increase, "financial_risk")
            
            risks.append(RiskAssessment(
                risk_id="cost_increase",
                description=f"成本上升风险：平均增长{avg_cost_increase:.2%}",
                category="财务风险",
                probability=0.6,
                impact=avg_cost_increase,
                risk_level=risk_level,
                mitigation_strategies=["成本控制", "供应商谈判", "流程优化"],
                estimated_cost=baseline.cost * avg_cost_increase,
                timeline="短期"
            ))
        
        return risks
    
    def _assess_operational_risks(self, scenarios: Dict[str, BusinessMetrics],
                                baseline: BusinessMetrics) -> List[RiskAssessment]:
        """
        评估运营风险
        """
        risks = []
        
        # 评估效率下降风险
        efficiency_drops = []
        for scenario_name, metrics in scenarios.items():
            efficiency_change = baseline.efficiency_score - metrics.efficiency_score
            if efficiency_change > 0:
                efficiency_drops.append(efficiency_change)
        
        if efficiency_drops:
            avg_efficiency_drop = np.mean(efficiency_drops)
            risk_level = self._determine_risk_level(avg_efficiency_drop, "operational_risk")
            
            risks.append(RiskAssessment(
                risk_id="efficiency_drop",
                description=f"效率下降风险：平均下降{avg_efficiency_drop:.2f}",
                category="运营风险",
                probability=0.5,
                impact=avg_efficiency_drop / 10,  # 标准化到0-1
                risk_level=risk_level,
                mitigation_strategies=self.risk_database["operational_risk"]["mitigation"],
                estimated_cost=baseline.revenue * 0.05,
                timeline="中期"
            ))
        
        return risks
    
    def _assess_market_risks(self, scenarios: Dict[str, BusinessMetrics],
                           baseline: BusinessMetrics) -> List[RiskAssessment]:
        """
        评估市场风险
        """
        risks = []
        
        # 评估市场份额损失风险
        market_share_losses = []
        for scenario_name, metrics in scenarios.items():
            share_change = baseline.market_share - metrics.market_share
            if share_change > 0:
                market_share_losses.append(share_change)
        
        if market_share_losses:
            avg_share_loss = np.mean(market_share_losses)
            risk_level = self._determine_risk_level(avg_share_loss, "market_risk")
            
            risks.append(RiskAssessment(
                risk_id="market_share_loss",
                description=f"市场份额损失风险：平均损失{avg_share_loss:.2%}",
                category="市场风险",
                probability=0.4,
                impact=avg_share_loss * 2,  # 市场份额损失影响较大
                risk_level=risk_level,
                mitigation_strategies=self.risk_database["market_risk"]["mitigation"],
                estimated_cost=baseline.revenue * avg_share_loss,
                timeline="中期-长期"
            ))
        
        return risks
    
    def _assess_compliance_risks(self, decision_data: Dict[str, Any]) -> List[RiskAssessment]:
        """
        评估合规风险
        """
        risks = []
        
        # 基于决策复杂度评估合规风险
        decision_complexity = len(decision_data.get('variables', []))
        constraint_count = len(decision_data.get('constraints', []))
        
        compliance_risk_score = min((decision_complexity + constraint_count) * 0.05, 1.0)
        
        if compliance_risk_score > 0.1:
            risk_level = self._determine_risk_level(compliance_risk_score, "compliance_risk")
            
            risks.append(RiskAssessment(
                risk_id="regulatory_compliance",
                description=f"监管合规风险：决策复杂度{decision_complexity}，约束条件{constraint_count}",
                category="合规风险",
                probability=compliance_risk_score,
                impact=0.7,
                risk_level=risk_level,
                mitigation_strategies=self.risk_database["compliance_risk"]["mitigation"],
                estimated_cost=100000,  # 假设合规成本
                timeline="持续"
            ))
        
        return risks
    
    def _determine_risk_level(self, risk_value: float, risk_type: str) -> RiskLevel:
        """
        确定风险等级
        """
        thresholds = self.risk_database[risk_type]["thresholds"]
        
        if risk_value < thresholds["low"]:
            return RiskLevel.LOW
        elif risk_value < thresholds["medium"]:
            return RiskLevel.MEDIUM
        elif risk_value < thresholds["high"]:
            return RiskLevel.HIGH
        else:
            return RiskLevel.CRITICAL


class OpportunityIdentifier:
    """
    机会识别器
    """
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
    
    def identify_opportunities(self, decision_data: Dict[str, Any],
                             scenario_metrics: Dict[str, BusinessMetrics],
                             baseline_metrics: BusinessMetrics,
                             risks: List[RiskAssessment]) -> List[BusinessOpportunity]:
        """
        识别商业机会
        
        Args:
            decision_data: 决策数据
            scenario_metrics: 情景指标
            baseline_metrics: 基准指标
            risks: 风险评估结果
            
        Returns:
            List[BusinessOpportunity]: 商业机会列表
        """
        opportunities = []
        
        try:
            # 识别成本降低机会
            cost_opportunities = self._identify_cost_reduction_opportunities(
                scenario_metrics, baseline_metrics
            )
            opportunities.extend(cost_opportunities)
            
            # 识别收入增长机会
            revenue_opportunities = self._identify_revenue_opportunities(
                scenario_metrics, baseline_metrics
            )
            opportunities.extend(revenue_opportunities)
            
            # 识别效率提升机会
            efficiency_opportunities = self._identify_efficiency_opportunities(
                scenario_metrics, baseline_metrics
            )
            opportunities.extend(efficiency_opportunities)
            
            # 识别风险缓解机会
            risk_mitigation_opportunities = self._identify_risk_mitigation_opportunities(risks)
            opportunities.extend(risk_mitigation_opportunities)
            
        except Exception as e:
            self.logger.error(f"机会识别失败: {e}")
        
        return sorted(opportunities, key=lambda x: x.expected_value, reverse=True)
    
    def _identify_cost_reduction_opportunities(self, scenarios: Dict[str, BusinessMetrics],
                                             baseline: BusinessMetrics) -> List[BusinessOpportunity]:
        """
        识别成本降低机会
        """
        opportunities = []
        
        # 找出成本最低的情景
        min_cost_scenario = min(scenarios.items(), key=lambda x: x[1].cost)
        min_cost = min_cost_scenario[1].cost
        
        if min_cost < baseline.cost:
            cost_saving = baseline.cost - min_cost
            
            opportunities.append(BusinessOpportunity(
                opportunity_id="cost_reduction_best_scenario",
                description=f"采用{min_cost_scenario[0]}方案可节省成本{cost_saving:.2f}",
                opportunity_type=OpportunityType.COST_REDUCTION,
                potential_value=cost_saving,
                implementation_cost=cost_saving * 0.1,  # 假设实施成本为节省金额的10%
                timeline="3-6个月",
                success_probability=0.8,
                required_resources=["项目团队", "变更管理", "培训"],
                dependencies=["管理层支持", "员工配合"]
            ))
        
        return opportunities
    
    def _identify_revenue_opportunities(self, scenarios: Dict[str, BusinessMetrics],
                                      baseline: BusinessMetrics) -> List[BusinessOpportunity]:
        """
        识别收入增长机会
        """
        opportunities = []
        
        # 找出收入最高的情景
        max_revenue_scenario = max(scenarios.items(), key=lambda x: x[1].revenue)
        max_revenue = max_revenue_scenario[1].revenue
        
        if max_revenue > baseline.revenue:
            revenue_increase = max_revenue - baseline.revenue
            
            opportunities.append(BusinessOpportunity(
                opportunity_id="revenue_increase_best_scenario",
                description=f"采用{max_revenue_scenario[0]}方案可增加收入{revenue_increase:.2f}",
                opportunity_type=OpportunityType.REVENUE_INCREASE,
                potential_value=revenue_increase,
                implementation_cost=revenue_increase * 0.2,  # 假设实施成本为增收金额的20%
                timeline="6-12个月",
                success_probability=0.7,
                required_resources=["销售团队", "市场推广", "产品开发"],
                dependencies=["市场需求", "竞争环境"]
            ))
        
        return opportunities
    
    def _identify_efficiency_opportunities(self, scenarios: Dict[str, BusinessMetrics],
                                         baseline: BusinessMetrics) -> List[BusinessOpportunity]:
        """
        识别效率提升机会
        """
        opportunities = []
        
        # 找出效率最高的情景
        max_efficiency_scenario = max(scenarios.items(), key=lambda x: x[1].efficiency_score)
        max_efficiency = max_efficiency_scenario[1].efficiency_score
        
        if max_efficiency > baseline.efficiency_score:
            efficiency_gain = max_efficiency - baseline.efficiency_score
            
            # 将效率提升转换为经济价值
            potential_value = baseline.revenue * (efficiency_gain / 100) * 0.5  # 假设效率提升50%转化为收入
            
            opportunities.append(BusinessOpportunity(
                opportunity_id="efficiency_improvement",
                description=f"采用{max_efficiency_scenario[0]}方案可提升效率{efficiency_gain:.2f}",
                opportunity_type=OpportunityType.EFFICIENCY_IMPROVEMENT,
                potential_value=potential_value,
                implementation_cost=potential_value * 0.15,
                timeline="3-9个月",
                success_probability=0.75,
                required_resources=["技术升级", "流程重组", "员工培训"],
                dependencies=["技术可行性", "组织变革"]
            ))
        
        return opportunities
    
    def _identify_risk_mitigation_opportunities(self, risks: List[RiskAssessment]) -> List[BusinessOpportunity]:
        """
        识别风险缓解机会
        """
        opportunities = []
        
        # 针对高风险项目创建缓解机会
        high_risks = [r for r in risks if r.risk_level in [RiskLevel.HIGH, RiskLevel.CRITICAL]]
        
        for risk in high_risks:
            potential_loss = risk.estimated_cost
            mitigation_cost = potential_loss * 0.3  # 假设缓解成本为潜在损失的30%
            
            opportunities.append(BusinessOpportunity(
                opportunity_id=f"mitigate_{risk.risk_id}",
                description=f"缓解{risk.description}的风险",
                opportunity_type=OpportunityType.RISK_MITIGATION,
                potential_value=potential_loss * risk.probability,  # 期望损失
                implementation_cost=mitigation_cost,
                timeline="1-6个月",
                success_probability=0.8,
                required_resources=risk.mitigation_strategies,
                dependencies=["风险监控", "应急预案"]
            ))
        
        return opportunities


class BusinessInsightGenerator:
    """
    商业洞察生成器
    """
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.impact_analyzer = DecisionImpactAnalyzer()
        self.risk_assessor = RiskAssessmentEngine()
        self.opportunity_identifier = OpportunityIdentifier()
    
    def generate_comprehensive_insights(self, decision_data: Dict[str, Any],
                                      scenario_results: Dict[str, Any],
                                      baseline_metrics: Optional[BusinessMetrics] = None) -> Dict[str, Any]:
        """
        生成综合商业洞察
        
        Args:
            decision_data: 决策数据
            scenario_results: 情景分析结果
            baseline_metrics: 基准指标
            
        Returns:
            Dict[str, Any]: 综合洞察报告
        """
        try:
            # 转换情景结果为业务指标
            scenario_metrics = self._convert_to_business_metrics(scenario_results)
            
            # 如果没有提供基准指标，使用平均值作为基准
            if baseline_metrics is None:
                baseline_metrics = self._calculate_baseline_metrics(scenario_metrics)
            
            # 分析决策影响
            impacts = self.impact_analyzer.analyze_decision_impact(
                decision_data, baseline_metrics, scenario_metrics
            )
            
            # 评估风险
            risks = self.risk_assessor.assess_risks(
                decision_data, scenario_metrics, baseline_metrics
            )
            
            # 识别机会
            opportunities = self.opportunity_identifier.identify_opportunities(
                decision_data, scenario_metrics, baseline_metrics, risks
            )
            
            # 生成洞察
            insights = self._generate_insights(
                decision_data, scenario_metrics, baseline_metrics, 
                impacts, risks, opportunities
            )
            
            # 生成建议
            recommendations = self._generate_recommendations(
                impacts, risks, opportunities
            )
            
            return {
                "executive_summary": self._generate_executive_summary(
                    scenario_metrics, baseline_metrics, risks, opportunities
                ),
                "decision_impacts": [self._impact_to_dict(impact) for impact in impacts],
                "risk_assessment": [self._risk_to_dict(risk) for risk in risks],
                "opportunities": [self._opportunity_to_dict(opp) for opp in opportunities],
                "insights": [self._insight_to_dict(insight) for insight in insights],
                "recommendations": recommendations,
                "key_metrics": self._calculate_key_metrics(scenario_metrics, baseline_metrics),
                "analysis_metadata": {
                    "analysis_date": datetime.now().isoformat(),
                    "scenarios_analyzed": len(scenario_metrics),
                    "risks_identified": len(risks),
                    "opportunities_found": len(opportunities),
                    "confidence_score": self._calculate_overall_confidence(impacts, risks, opportunities)
                }
            }
            
        except Exception as e:
            self.logger.error(f"商业洞察生成失败: {e}")
            return {"error": f"洞察生成失败: {str(e)}"}
    
    def _convert_to_business_metrics(self, scenario_results: Dict[str, Any]) -> Dict[str, BusinessMetrics]:
        """
        将情景结果转换为业务指标
        """
        metrics = {}
        
        for scenario_name, result in scenario_results.items():
            # 从结果中提取关键指标
            profit = result.get('profit', result.get('objective_value', 0))
            cost = result.get('cost', 0)
            revenue = profit + cost if cost > 0 else profit * 1.5  # 估算收入
            
            metrics[scenario_name] = BusinessMetrics(
                revenue=revenue,
                cost=cost,
                profit=profit,
                efficiency_score=result.get('efficiency', 75),  # 默认效率分数
                quality_score=result.get('quality', 80),  # 默认质量分数
                customer_satisfaction=result.get('satisfaction', 75),  # 默认满意度
                market_share=result.get('market_share', 0.1),  # 默认市场份额
                risk_score=result.get('risk', 0.3)  # 默认风险分数
            )
        
        return metrics
    
    def _calculate_baseline_metrics(self, scenario_metrics: Dict[str, BusinessMetrics]) -> BusinessMetrics:
        """
        计算基准指标（使用平均值）
        """
        if not scenario_metrics:
            return BusinessMetrics()
        
        metrics_list = list(scenario_metrics.values())
        
        return BusinessMetrics(
            revenue=np.mean([m.revenue for m in metrics_list]),
            cost=np.mean([m.cost for m in metrics_list]),
            profit=np.mean([m.profit for m in metrics_list]),
            efficiency_score=np.mean([m.efficiency_score for m in metrics_list]),
            quality_score=np.mean([m.quality_score for m in metrics_list]),
            customer_satisfaction=np.mean([m.customer_satisfaction for m in metrics_list]),
            market_share=np.mean([m.market_share for m in metrics_list]),
            risk_score=np.mean([m.risk_score for m in metrics_list])
        )
    
    def _generate_insights(self, decision_data: Dict[str, Any],
                          scenario_metrics: Dict[str, BusinessMetrics],
                          baseline_metrics: BusinessMetrics,
                          impacts: List[DecisionImpact],
                          risks: List[RiskAssessment],
                          opportunities: List[BusinessOpportunity]) -> List[BusinessInsight]:
        """
        生成商业洞察
        """
        insights = []
        
        # 洞察1：最优情景分析
        best_scenario = max(scenario_metrics.items(), key=lambda x: x[1].profit)
        insights.append(BusinessInsight(
            insight_id="best_scenario_analysis",
            title="最优决策方案识别",
            description=f"在所有分析的情景中，{best_scenario[0]}表现最佳，利润为{best_scenario[1].profit:.2f}",
            insight_type="决策优化",
            priority="高",
            confidence=0.9,
            supporting_data={"scenario": best_scenario[0], "profit": best_scenario[1].profit},
            recommendations=[f"建议采用{best_scenario[0]}方案", "监控关键绩效指标", "制定实施计划"],
            potential_impact=best_scenario[1].profit - baseline_metrics.profit,
            implementation_difficulty="中等",
            timeline="3-6个月"
        ))
        
        # 洞察2：风险-收益权衡
        high_risks = [r for r in risks if r.risk_level in [RiskLevel.HIGH, RiskLevel.CRITICAL]]
        if high_risks:
            total_risk_exposure = sum(r.risk_score * r.estimated_cost for r in high_risks)
            insights.append(BusinessInsight(
                insight_id="risk_return_tradeoff",
                title="风险-收益权衡分析",
                description=f"识别出{len(high_risks)}个高风险项目，总风险敞口{total_risk_exposure:.2f}",
                insight_type="风险管理",
                priority="高",
                confidence=0.8,
                supporting_data={"high_risks": len(high_risks), "risk_exposure": total_risk_exposure},
                recommendations=["制定风险缓解策略", "建立风险监控机制", "准备应急预案"],
                potential_impact=-total_risk_exposure * 0.3,  # 负面影响
                implementation_difficulty="高",
                timeline="持续"
            ))
        
        # 洞察3：机会价值分析
        if opportunities:
            total_opportunity_value = sum(opp.expected_value for opp in opportunities)
            insights.append(BusinessInsight(
                insight_id="opportunity_value_analysis",
                title="机会价值最大化",
                description=f"识别出{len(opportunities)}个商业机会，总期望价值{total_opportunity_value:.2f}",
                insight_type="机会识别",
                priority="中",
                confidence=0.7,
                supporting_data={"opportunities": len(opportunities), "total_value": total_opportunity_value},
                recommendations=["优先实施高价值机会", "评估资源需求", "制定实施路线图"],
                potential_impact=total_opportunity_value,
                implementation_difficulty="中等",
                timeline="6-12个月"
            ))
        
        return insights
    
    def _generate_recommendations(self, impacts: List[DecisionImpact],
                                risks: List[RiskAssessment],
                                opportunities: List[BusinessOpportunity]) -> List[str]:
        """
        生成建议
        """
        recommendations = []
        
        # 基于影响分析的建议
        positive_impacts = [i for i in impacts if i.total_impact > 0]
        if positive_impacts:
            recommendations.append("重点关注具有正面影响的决策领域，确保充分发挥其价值")
        
        # 基于风险评估的建议
        critical_risks = [r for r in risks if r.risk_level == RiskLevel.CRITICAL]
        if critical_risks:
            recommendations.append("立即制定严重风险的应对措施，避免重大损失")
        
        high_risks = [r for r in risks if r.risk_level == RiskLevel.HIGH]
        if high_risks:
            recommendations.append("建立高风险项目的监控机制，定期评估风险状态")
        
        # 基于机会识别的建议
        high_value_opportunities = [o for o in opportunities if o.expected_value > 10000]
        if high_value_opportunities:
            recommendations.append("优先投资高价值机会，确保资源配置的最优化")
        
        # 通用建议
        recommendations.extend([
            "建立定期的决策效果评估机制",
            "保持决策的灵活性，根据市场变化及时调整",
            "加强跨部门协作，确保决策的有效执行",
            "投资于数据分析能力，提高决策的科学性"
        ])
        
        return recommendations
    
    def _generate_executive_summary(self, scenario_metrics: Dict[str, BusinessMetrics],
                                  baseline_metrics: BusinessMetrics,
                                  risks: List[RiskAssessment],
                                  opportunities: List[BusinessOpportunity]) -> str:
        """
        生成执行摘要
        """
        best_scenario = max(scenario_metrics.items(), key=lambda x: x[1].profit)
        worst_scenario = min(scenario_metrics.items(), key=lambda x: x[1].profit)
        
        profit_range = best_scenario[1].profit - worst_scenario[1].profit
        high_risks = len([r for r in risks if r.risk_level in [RiskLevel.HIGH, RiskLevel.CRITICAL]])
        total_opportunity_value = sum(opp.expected_value for opp in opportunities)
        
        summary = f"""
        **决策分析执行摘要**
        
        本次分析涵盖了{len(scenario_metrics)}个决策情景，利润范围从{worst_scenario[1].profit:.2f}到{best_scenario[1].profit:.2f}，
        差异为{profit_range:.2f}。
        
        **关键发现：**
        - 最优方案：{best_scenario[0]}，预期利润{best_scenario[1].profit:.2f}
        - 风险状况：识别出{len(risks)}个风险项目，其中{high_risks}个为高风险
        - 机会价值：发现{len(opportunities)}个商业机会，总期望价值{total_opportunity_value:.2f}
        
        **建议：**
        建议采用{best_scenario[0]}方案，同时制定相应的风险缓解措施和机会实现计划。
        """
        
        return summary.strip()
    
    def _calculate_key_metrics(self, scenario_metrics: Dict[str, BusinessMetrics],
                             baseline_metrics: BusinessMetrics) -> Dict[str, float]:
        """
        计算关键指标
        """
        profits = [m.profit for m in scenario_metrics.values()]
        
        return {
            "max_profit": max(profits),
            "min_profit": min(profits),
            "avg_profit": np.mean(profits),
            "profit_volatility": np.std(profits),
            "profit_improvement_potential": max(profits) - baseline_metrics.profit,
            "downside_risk": baseline_metrics.profit - min(profits)
        }
    
    def _calculate_overall_confidence(self, impacts: List[DecisionImpact],
                                    risks: List[RiskAssessment],
                                    opportunities: List[BusinessOpportunity]) -> float:
        """
        计算整体置信度
        """
        impact_confidence = np.mean([i.confidence_level for i in impacts]) if impacts else 0.5
        risk_confidence = 1.0 - (len([r for r in risks if r.risk_level == RiskLevel.CRITICAL]) * 0.2)
        opportunity_confidence = np.mean([o.success_probability for o in opportunities]) if opportunities else 0.5
        
        return (impact_confidence + risk_confidence + opportunity_confidence) / 3
    
    # 辅助方法：转换为字典格式
    def _impact_to_dict(self, impact: DecisionImpact) -> Dict[str, Any]:
        return {
            "decision_id": impact.decision_id,
            "description": impact.description,
            "category": impact.category.value,
            "short_term_impact": impact.short_term_impact,
            "medium_term_impact": impact.medium_term_impact,
            "long_term_impact": impact.long_term_impact,
            "total_impact": impact.total_impact,
            "confidence_level": impact.confidence_level,
            "affected_stakeholders": impact.affected_stakeholders,
            "metrics_affected": impact.metrics_affected
        }
    
    def _risk_to_dict(self, risk: RiskAssessment) -> Dict[str, Any]:
        return {
            "risk_id": risk.risk_id,
            "description": risk.description,
            "category": risk.category,
            "probability": risk.probability,
            "impact": risk.impact,
            "risk_level": risk.risk_level.value,
            "risk_score": risk.risk_score,
            "mitigation_strategies": risk.mitigation_strategies,
            "estimated_cost": risk.estimated_cost,
            "timeline": risk.timeline
        }
    
    def _opportunity_to_dict(self, opportunity: BusinessOpportunity) -> Dict[str, Any]:
        return {
            "opportunity_id": opportunity.opportunity_id,
            "description": opportunity.description,
            "opportunity_type": opportunity.opportunity_type.value,
            "potential_value": opportunity.potential_value,
            "implementation_cost": opportunity.implementation_cost,
            "net_value": opportunity.net_value,
            "expected_value": opportunity.expected_value,
            "roi_potential": opportunity.roi_potential,
            "timeline": opportunity.timeline,
            "success_probability": opportunity.success_probability,
            "required_resources": opportunity.required_resources,
            "dependencies": opportunity.dependencies
        }
    
    def _insight_to_dict(self, insight: BusinessInsight) -> Dict[str, Any]:
        return {
            "insight_id": insight.insight_id,
            "title": insight.title,
            "description": insight.description,
            "insight_type": insight.insight_type,
            "priority": insight.priority,
            "confidence": insight.confidence,
            "supporting_data": insight.supporting_data,
            "recommendations": insight.recommendations,
            "potential_impact": insight.potential_impact,
            "implementation_difficulty": insight.implementation_difficulty,
            "timeline": insight.timeline
        }


def create_business_insight_generator() -> BusinessInsightGenerator:
    """
    创建商业洞察生成器实例
    
    Returns:
        BusinessInsightGenerator: 商业洞察生成器实例
    """
    return BusinessInsightGenerator()